package com.yst.webplugin.fieldhandler;

import com.yst.spring.context.SpringContext;
import com.yst.web.utils.BeanUtils;
import com.yst.web.utils.ClassUtils;
import com.yst.webplugin.annotation.Delete;
import com.yst.webplugin.annotation.DeleteType;
import com.yst.webplugin.annotation.HttpInfo;
import com.yst.webplugin.loginplugin.UserUtils;
import com.yst.webplugin.util.ReqParamsUtils;
import lombok.SneakyThrows;
import org.sagacity.sqltoy.dao.SqlToyLazyDao;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;

public class DeleteHandler implements IFieldHandler{
    @Override
    public boolean accept(Field field) {
        return Objects.nonNull(field.getAnnotation(Delete.class));
    }

    @SneakyThrows
    @Transactional
    @Override
    public void handle(Field field, HttpInfo httpInfo) {
        Delete delete = field.getAnnotation(Delete.class);
        SqlToyLazyDao sqlToyLazyDao = SpringContext.getContext().getBean(SqlToyLazyDao.class);
        String body=httpInfo.getBody();
        List<Serializable> modelList=new LinkedList<>();
        if (ReqParamsUtils.isArray(body)){
            List<Object> idList=ReqParamsUtils.getParamAsList(body,Object.class);
            for (Object id:idList){
                Serializable model=delete.modelClass().newInstance();
                BeanUtils.setFieldValue(delete.keyField(), model,id);
                model=sqlToyLazyDao.load(model);
                modelList.add(model);
            }
        }
        else {
            Serializable model=httpInfo.getBodyAs(delete.modelClass());
            model=sqlToyLazyDao.load(model);
            modelList.add(model);
        }

        for (Serializable model:modelList) {
            if (delete.deleteType() == DeleteType.logic) {
                if (ClassUtils.classExistsField(delete.modelClass(), delete.deleteUserId())) {
                    BeanUtils.setFieldValue(delete.deleteUserId(), model, UserUtils.getCurrentUserId());
                }
                if (ClassUtils.classExistsField(delete.modelClass(), delete.deleteTime())) {
                    BeanUtils.setFieldValue(delete.deleteTime(), model, new Date());
                }
                sqlToyLazyDao.update(model);
            } else {
                sqlToyLazyDao.delete(model);
            }
        }
        httpInfo.writeResult(true);
    }

}
